<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="项目经常用到把当前页面导出为pdf，或者生成某个页面或部分的快照。如果是简单的页面快照，不没有太多的渲染，可以用html2canvas.min.js导出图片或者html2pdf.bundle.min.js导出为pdf，仅仅在前端就可以完成。但是复杂的页面，以上的导出效果不好，质量也不高。因此我采用PhantomJS，用后台生成pdf、png等进行导出。 1.PhantomJS简介 PhantomJ">
<meta property="og:type" content="article">
<meta property="og:title" content="在线HTML页面导出pdf或图片,支持模拟跳过登陆验证">
<meta property="og:url" content="http://weiller.com/2019/09/10/2019-09-10-在线HTML页面导出pdf或图片,支持模拟跳过登陆验证/index.html">
<meta property="og:site_name" content="WeillerBlog">
<meta property="og:description" content="项目经常用到把当前页面导出为pdf，或者生成某个页面或部分的快照。如果是简单的页面快照，不没有太多的渲染，可以用html2canvas.min.js导出图片或者html2pdf.bundle.min.js导出为pdf，仅仅在前端就可以完成。但是复杂的页面，以上的导出效果不好，质量也不高。因此我采用PhantomJS，用后台生成pdf、png等进行导出。 1.PhantomJS简介 PhantomJ">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://weiller.com/2019/09/10/images/java/phantomjs目录截图.jpg">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20190912142654887.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpd2VpbGxlcg==,size_16,color_FFFFFF,t_70">
<meta property="og:updated_time" content="2019-09-17T07:39:00.902Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="在线HTML页面导出pdf或图片,支持模拟跳过登陆验证">
<meta name="twitter:description" content="项目经常用到把当前页面导出为pdf，或者生成某个页面或部分的快照。如果是简单的页面快照，不没有太多的渲染，可以用html2canvas.min.js导出图片或者html2pdf.bundle.min.js导出为pdf，仅仅在前端就可以完成。但是复杂的页面，以上的导出效果不好，质量也不高。因此我采用PhantomJS，用后台生成pdf、png等进行导出。 1.PhantomJS简介 PhantomJ">
<meta name="twitter:image" content="http://weiller.com/2019/09/10/images/java/phantomjs目录截图.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://weiller.com/2019/09/10/2019-09-10-在线HTML页面导出pdf或图片,支持模拟跳过登陆验证/">





  <title>在线HTML页面导出pdf或图片,支持模拟跳过登陆验证 | WeillerBlog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	<!-- 右上角github图标 -->
<a href="https://github.com/xiweile" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
	<!-- 右上角github图标 -->   
   <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">WeillerBlog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">惠维乐个人博客</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://weiller.com/2019/09/10/2019-09-10-在线HTML页面导出pdf或图片,支持模拟跳过登陆验证/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="惠维乐">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="WeillerBlog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">在线HTML页面导出pdf或图片,支持模拟跳过登陆验证</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-10T10:00:00+08:00">
                2019-09-10
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/09/10/2019-09-10-在线HTML页面导出pdf或图片,支持模拟跳过登陆验证/" class="leancloud_visitors" data-flag-title="在线HTML页面导出pdf或图片,支持模拟跳过登陆验证">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>项目经常用到把当前页面导出为pdf，或者生成某个页面或部分的快照。如果是简单的页面快照，不没有太多的渲染，可以用<code>html2canvas.min.js</code>导出图片或者<code>html2pdf.bundle.min.js</code>导出为pdf，仅仅在前端就可以完成。但是复杂的页面，以上的导出效果不好，质量也不高。因此我采用<code>PhantomJS</code>，用后台生成pdf、png等进行导出。</p>
<h3 id="1-PhantomJS简介"><a href="#1-PhantomJS简介" class="headerlink" title="1.PhantomJS简介"></a>1.PhantomJS简介</h3><blockquote>
<p>PhantomJS是一个基于webkit的JavaScript API。它使用QtWebKit作为它核心浏览器的功能，使用webkit来编译解释执行JavaScript代码。任何你可以在基于webkit浏览器做的事情，它都能做到。它不仅是个隐形的浏览器，提供了诸如CSS选择器、支持Web标准、DOM操作、JSON、HTML5、Canvas、SVG等，同时也提供了处理文件I/O的操作，从而使你可以向操作系统读写文件等。PhantomJS的用处可谓非常广泛，诸如网络监测、网页截屏、无需浏览器的 Web 测试、页面访问自动化等。</p>
</blockquote>
<h3 id="2-下载及安装"><a href="#2-下载及安装" class="headerlink" title="2.下载及安装"></a>2.下载及安装</h3><p>官方下载地址：<a href="http://phantomjs.org/download.html" target="_blank" rel="noopener">http://phantomjs.org/download.html</a>。目前官方支持三种操作系统，包括windows\Mac OS\Linux这三大主流的环境。根据运行环境选择要下载的包，下面以Windows7为例，我将phantomjs文件放置到D盘根目录下，里面的内容如下图。</p>
<p><img src="../images/java/phantomjs目录截图.jpg" alt="image"></p>
<h3 id="3-如何使用"><a href="#3-如何使用" class="headerlink" title="3.如何使用"></a>3.如何使用</h3><h4 id="1-准备一个配置的js文件"><a href="#1-准备一个配置的js文件" class="headerlink" title="1) 准备一个配置的js文件"></a>1) 准备一个配置的js文件</h4><p>在D盘phantomjs目录下新建一个<code>html2pdf.js</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * phantomJs 脚本 html转图片</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> page = <span class="built_in">require</span>(<span class="string">'webpage'</span>).create(),</span><br><span class="line">	system = <span class="built_in">require</span>(<span class="string">'system'</span>), </span><br><span class="line">	address, output, size,JSESSIONID,domain;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (system.args.length &lt; <span class="number">3</span> || system.args.length &gt; <span class="number">5</span>) &#123;</span><br><span class="line">    phantom.exit(<span class="number">1</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line"> </span><br><span class="line">    address = system.args[<span class="number">1</span>];</span><br><span class="line">    output = system.args[<span class="number">2</span>];</span><br><span class="line">	<span class="keyword">if</span>(system.args.length&gt;<span class="number">3</span>)&#123;</span><br><span class="line">		JSESSIONID = system.args[<span class="number">3</span>];</span><br><span class="line">		domain = system.args[<span class="number">4</span>];</span><br><span class="line">		</span><br><span class="line">		 <span class="comment">// 添加cookie</span></span><br><span class="line">		phantom.addCookie(&#123;</span><br><span class="line">			  <span class="string">"name"</span>:<span class="string">"JSESSIONID"</span>,</span><br><span class="line">			  <span class="string">"value"</span>:JSESSIONID,</span><br><span class="line">			  <span class="string">"domain"</span>:domain, </span><br><span class="line">			  <span class="string">"path"</span>:<span class="string">"/"</span>,</span><br><span class="line">			  <span class="string">"httponly"</span>:<span class="literal">false</span>,</span><br><span class="line">			  <span class="string">"secure"</span>:<span class="literal">false</span>,</span><br><span class="line">			  <span class="string">"expires"</span>: <span class="string">"Fri, 01 Jan 2038 00:00:00 GMT"</span></span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="comment">//定义浏览器宽高</span></span><br><span class="line">    page.viewportSize = &#123;</span><br><span class="line">        width : <span class="number">2048</span>,</span><br><span class="line">        height : <span class="number">768</span></span><br><span class="line">    &#125;; </span><br><span class="line"></span><br><span class="line">	<span class="comment">// 纸张尺寸</span></span><br><span class="line">	page.paperSize = &#123;</span><br><span class="line">	 format: <span class="string">'A3'</span>,</span><br><span class="line">	 orientation: <span class="string">'landscape'</span>,<span class="comment">//横向</span></span><br><span class="line">	  margin: &#123; </span><br><span class="line">		left:<span class="string">"2cm"</span>, </span><br><span class="line">		right:<span class="string">"2cm"</span>, </span><br><span class="line">		top:<span class="string">"1cm"</span>, </span><br><span class="line">		bottom:<span class="string">"1cm"</span> </span><br><span class="line">	  &#125; </span><br><span class="line"> </span><br><span class="line">	&#125;;  </span><br><span class="line">    page.open(address, <span class="function"><span class="keyword">function</span>(<span class="params">status</span>) </span>&#123;</span><br><span class="line">		 <span class="built_in">console</span>.log(<span class="string">'Status: '</span> + status);</span><br><span class="line">		 <span class="keyword">if</span> (status !== <span class="string">'success'</span>) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'Unable to load the address!'</span>);</span><br><span class="line">            phantom.exit(<span class="number">1</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">var</span> bb = page.evaluate(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">			<span class="comment">//var child=document.getElementById("printBt");</span></span><br><span class="line">			<span class="comment">//child.parentNode.removeChild(child);//此外可以写一些对页面操作的代码，比如词句代码是删除页面上的打印按钮</span></span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">document</span>.getElementsByTagName(<span class="string">'html'</span>)[<span class="number">0</span>].getBoundingClientRect();<span class="comment">//返回内容就是要导出的范围（此处是HTML整页）</span></span><br><span class="line">			&#125;);</span><br><span class="line">			<span class="comment">// 截取范围</span></span><br><span class="line">			page.clipRect = &#123;</span><br><span class="line">				top : bb.top,</span><br><span class="line">				left : bb.left,</span><br><span class="line">				width : bb.width,</span><br><span class="line">				height : bb.height</span><br><span class="line">			&#125;;</span><br><span class="line">			</span><br><span class="line">			<span class="comment">// 等待页面渲染</span></span><br><span class="line">			<span class="built_in">window</span>.setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">				page.render(output, &#123;<span class="attr">format</span>: <span class="string">'pdf'</span>, <span class="attr">quality</span>: <span class="string">'100'</span>&#125;);<span class="comment">//这里配置导出的格式pdf,png等，quality为导出质量</span></span><br><span class="line">				page.close();</span><br><span class="line">				<span class="built_in">console</span>.log(<span class="string">'渲染成功...'</span>);</span><br><span class="line">				phantom.exit();</span><br><span class="line">			&#125;, <span class="number">2000</span>);</span><br><span class="line">        &#125;</span><br><span class="line">       </span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line">address = system.args[<span class="number">1</span>];<span class="comment">//传入的URL地址</span></span><br><span class="line">output = system.args[<span class="number">2</span>];<span class="comment">//保存的图片路径</span></span><br></pre></td></tr></table></figure>
<h4 id="2）测试命令"><a href="#2）测试命令" class="headerlink" title="2）测试命令"></a>2）测试命令</h4><p> 例如：phantomjs文件夹放于D盘根目录，在phantomjs/bin 目录下（也可以配置环境变量）打开控制台。以我的CSDN博客页面<code>https://blog.csdn.net/xiweiller</code>导出为PDF为例。输入如下命令:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">phantomjs.exe D:/phantomjs/html2pdf.js https://blog.csdn.net/xiweiller D:/phantomjs/blog.pdf</span><br></pre></td></tr></table></figure>
<p>其中 <code>phantomjs.exe</code>是执行命令文件，  <code>D:/phantomjs/screenshot.js</code>是执行的配置js文件，<code>https://blog.csdn.net/xiweiller</code>是目标HTML，<code>D:/phantomjs/blog.pdf</code>是导出PDF的路径。</p>
<h4 id="3）-java中的使用，springboot项目为例"><a href="#3）-java中的使用，springboot项目为例" class="headerlink" title="3） java中的使用，springboot项目为例"></a>3） java中的使用，springboot项目为例</h4><ul>
<li><p>application.yml中添加配置，配置项为phantomjs执行文件路径</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">htmltopdf:</span></span><br><span class="line"><span class="attr">  path:</span></span><br><span class="line"><span class="attr">    windows:</span> <span class="attr">D:/phantomjs/bin/phantomjs.exe</span></span><br><span class="line"><span class="attr">    linux:</span> <span class="string">/root/soft/phantomjs-2.1.1-linux-x86_64/bin/phantomjs</span></span><br><span class="line"><span class="attr">    mac:</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>Html转Pdf工具类</p>
<p>参数：</p>
<pre><code>- htmlPath 目标网页访问地址
- pdfPath 导出pdf存放目录
- JSESSIONID  登陆认证时需要传递，用于cookie携带
- domain cookie中获取
</code></pre></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Html转Pdf工具类</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HtmlToPdf</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Value</span>(<span class="string">"$&#123;htmltopdf.path.windows&#125;"</span>)</span><br><span class="line">	<span class="keyword">private</span> String WINDOWS_WKHTMLTOPDF_PATH;</span><br><span class="line">	<span class="meta">@Value</span>(<span class="string">"$&#123;htmltopdf.path.mac&#125;"</span>)</span><br><span class="line">	<span class="keyword">private</span> String MAC_WKHTMLTOPDF_PATH;</span><br><span class="line">	<span class="meta">@Value</span>(<span class="string">"$&#123;htmltopdf.path.linux&#125;"</span>)</span><br><span class="line">	<span class="keyword">private</span> String LINUX_WKHTMLTOPDF_PATH;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> Logger log = LoggerFactory.getLogger(HtmlToPdf.class);</span><br><span class="line">	</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * html转pdf核心方法</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> htmlPath html路径（硬盘和网盘路径都支持）</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> pdfPath pdf存储路径</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> 转换成功：true，失败：false</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span>  <span class="keyword">boolean</span> <span class="title">convert</span><span class="params">(String htmlPath, String pdfPath,String JSESSIONID,String domain)</span> </span>&#123;</span><br><span class="line">		File file = <span class="keyword">new</span> File(pdfPath);</span><br><span class="line">		File parent = file.getParentFile();</span><br><span class="line">		<span class="keyword">if</span> (!parent.exists()) &#123;<span class="comment">// 如果pdf保存路径不存在，则创建路径</span></span><br><span class="line">			parent.mkdirs();</span><br><span class="line">		&#125;</span><br><span class="line">		String toolDir = <span class="keyword">null</span>;<span class="comment">//   转换工具在系统中的路径</span></span><br><span class="line">		<span class="keyword">if</span> (System.getProperty(<span class="string">"os.name"</span>).indexOf(<span class="string">"Windows"</span>) != -<span class="number">1</span>) &#123;<span class="comment">//windows 系统</span></span><br><span class="line">			toolDir = WINDOWS_WKHTMLTOPDF_PATH;</span><br><span class="line">		&#125;<span class="keyword">else</span> <span class="keyword">if</span>(System.getProperty(<span class="string">"os.name"</span>).indexOf(<span class="string">"Mac OS X"</span>) != -<span class="number">1</span>)&#123;<span class="comment">//mac 系统</span></span><br><span class="line">			toolDir = MAC_WKHTMLTOPDF_PATH;</span><br><span class="line">		&#125;<span class="keyword">else</span> <span class="keyword">if</span>(System.getProperty(<span class="string">"os.name"</span>).indexOf(<span class="string">"Linux"</span>) != -<span class="number">1</span>)&#123;<span class="comment">//linux 系统</span></span><br><span class="line">			toolDir = LINUX_WKHTMLTOPDF_PATH;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">boolean</span> result = <span class="keyword">true</span>;<span class="comment">//pdf创建成功标识，默认成功</span></span><br><span class="line">		String BLANK = <span class="string">" "</span>;<span class="comment">//空格</span></span><br><span class="line">		Process process = <span class="keyword">null</span>;<span class="comment">//图片输出路径</span></span><br><span class="line">		StringBuffer sbf = <span class="keyword">null</span>;</span><br><span class="line">		InputStream is = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">		StringBuilder cmd = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">		cmd.append(toolDir)</span><br><span class="line">				.append(BLANK)</span><br><span class="line">				.append(<span class="keyword">new</span> File(toolDir).getParent()).append(File.separator).append(<span class="string">"html2pdf.js"</span>)</span><br><span class="line">				.append(BLANK)</span><br><span class="line">				.append(htmlPath)</span><br><span class="line">				.append(BLANK)</span><br><span class="line">				.append(pdfPath);</span><br><span class="line">		<span class="keyword">if</span>(JSESSIONID!=<span class="keyword">null</span>)&#123;<span class="comment">//添加cookie值</span></span><br><span class="line">			cmd.append(BLANK).append(JSESSIONID);</span><br><span class="line">			cmd.append(BLANK).append(domain);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			log.info(<span class="string">"报表准备导出 "</span> );</span><br><span class="line">			log.info(<span class="string">"导出命令：&#123;&#125;"</span>,cmd.toString() );</span><br><span class="line">			process = Runtime.getRuntime().exec(cmd.toString());<span class="comment">// 输出路径</span></span><br><span class="line"></span><br><span class="line">			is = process.getInputStream();</span><br><span class="line">			BufferedReader br = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> InputStreamReader(is));</span><br><span class="line">			sbf = <span class="keyword">new</span> StringBuffer();</span><br><span class="line">			String tmp = <span class="string">""</span>;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">while</span> ((tmp = br.readLine()) != <span class="keyword">null</span>) &#123;</span><br><span class="line">				sbf.append(tmp);</span><br><span class="line">			&#125;</span><br><span class="line">			log.info(<span class="string">"报表导出完成 "</span> );</span><br><span class="line">		&#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">			result = <span class="keyword">false</span>;</span><br><span class="line">			log.error(<span class="string">"报表导出失败！"</span>, e);</span><br><span class="line">		&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">			<span class="keyword">if</span> (is != <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">try</span> &#123;</span><br><span class="line">					is.close();</span><br><span class="line">				&#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">					e.printStackTrace();</span><br><span class="line">				&#125;</span><br><span class="line">				is = <span class="keyword">null</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> result;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><p>转换工具的调用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">( HttpServletRequest request )</span></span>&#123;</span><br><span class="line">      		<span class="comment">// 注意不同部署环境，路径不同。</span></span><br><span class="line">		String htmlUrl = <span class="string">"D:/phantomjs/html2pdf.js"</span>;</span><br><span class="line">		String pdfPath =  <span class="string">"D:/phantomjs/export.pdf"</span></span><br><span class="line">		String JSESSIONID = <span class="string">""</span>;</span><br><span class="line">		String domain =  request.getServerName();</span><br><span class="line">		Cookie[] cookies = request.getCookies();</span><br><span class="line">		<span class="keyword">for</span>(Cookie cookie :cookies)&#123;</span><br><span class="line">			<span class="keyword">if</span>(<span class="string">"JSESSIONID"</span>.equals(cookie.getName()))&#123;</span><br><span class="line">				JSESSIONID = cookie.getValue();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">//将html转换为pdf文件</span></span><br><span class="line">		<span class="keyword">boolean</span> isno =htmlToPdf.convert(htmlUrl,pdfPath,JSESSIONID,domain);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="4-导出效果图"><a href="#4-导出效果图" class="headerlink" title="4) 导出效果图"></a>4) 导出效果图</h4><p><img src="https://img-blog.csdnimg.cn/20190912142654887.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpd2VpbGxlcg==,size_16,color_FFFFFF,t_70" alt="页面导出效果"></p>
<h3 id="4-注意事项"><a href="#4-注意事项" class="headerlink" title="4. 注意事项"></a>4. 注意事项</h3><p>​    在实际项目使用时，我们必须保证页面异步加载的速度比较快，否则会出现页面渲染不完整的问题。因此在项目中，被导出的目标页面最好能做到快速响应，尽量减少异步请求加载，或者保证异步接口快速响应。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>继续努力吧！来一个</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="惠维乐 微信支付">
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/09/01/2019-09-01-简单的HTML快照生成,导出pdf或图片/" rel="next" title="简单的HTML快照生成,导出pdf或图片">
                <i class="fa fa-chevron-left"></i> 简单的HTML快照生成,导出pdf或图片
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/09/10/2019-09-10-springcloud zuul源码分析：内置过滤器/" rel="prev" title="springcloud zuul源码分析：内置过滤器">
                springcloud zuul源码分析：内置过滤器 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="惠维乐">
            
              <p class="site-author-name" itemprop="name">惠维乐</p>
              <p class="site-description motion-element" itemprop="description">IT技术文章/JAVA学习分享/个人随笔</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/xiweile" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/xiweiller" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-copyright"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:weiller@126.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-PhantomJS简介"><span class="nav-number">1.</span> <span class="nav-text">1.PhantomJS简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-下载及安装"><span class="nav-number">2.</span> <span class="nav-text">2.下载及安装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-如何使用"><span class="nav-number">3.</span> <span class="nav-text">3.如何使用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-准备一个配置的js文件"><span class="nav-number">3.1.</span> <span class="nav-text">1) 准备一个配置的js文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2）测试命令"><span class="nav-number">3.2.</span> <span class="nav-text">2）测试命令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3）-java中的使用，springboot项目为例"><span class="nav-number">3.3.</span> <span class="nav-text">3） java中的使用，springboot项目为例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-导出效果图"><span class="nav-number">3.4.</span> <span class="nav-text">4) 导出效果图</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-注意事项"><span class="nav-number">4.</span> <span class="nav-text">4. 注意事项</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">惠维乐</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-users"></i> 本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








  <div>
    <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1276853944'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s5.cnzz.com/z_stat.php%3Fid%3D1276853944%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("e7h0BlhhzchHRhKnkOXA3Xiy-gzGzoHsz", "RfdAeLEHuGFEEFwJleHOnszU");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
